package org.jeecg.modules.wms.outOrder.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.wms.common.constant.CommonWms;
import org.jeecg.modules.wms.common.service.IWmsGetCommonServiceImpl;
import org.jeecg.modules.wms.inOrder.entity.WmsOrderHeader;
import org.jeecg.modules.wms.inventory.entity.WmsInventory;
import org.jeecg.modules.wms.inventory.mapper.WmsInventoryMapper;
import org.jeecg.modules.wms.inventory.service.IWmsInventoryService;
import org.jeecg.modules.wms.outOrder.entity.WmsOutOrderHeader;
import org.jeecg.modules.wms.outOrder.entity.WmsOutOrderLine;
import org.jeecg.modules.wms.outOrder.mapper.WmsOutOrderLineMapper;
import org.jeecg.modules.wms.outOrder.mapper.WmsOutOrderHeaderMapper;
import org.jeecg.modules.wms.outOrder.service.IWmsOutOrderHeaderService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 出库单主表
 * @Author: jeecg-boot
 * @Date: 2023-11-13
 * @Version: V1.0
 */
@Service
public class WmsOutOrderHeaderServiceImpl extends ServiceImpl<WmsOutOrderHeaderMapper, WmsOutOrderHeader> implements IWmsOutOrderHeaderService {

    @Autowired
    private WmsOutOrderHeaderMapper wmsOutOrderHeaderMapper;
    @Autowired
    private WmsOutOrderLineMapper wmsOutOrderLineMapper;
    @Autowired
    private IWmsGetCommonServiceImpl wmsGetNameService;
    @Autowired
    private WmsInventoryMapper wmsInventoryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(WmsOutOrderHeader wmsOutOrderHeader, List<WmsOutOrderLine> wmsOutOrderLineList) {
        wmsOutOrderHeaderMapper.insert(wmsOutOrderHeader);
        if (wmsOutOrderLineList != null && wmsOutOrderLineList.size() > 0) {
            for (WmsOutOrderLine entity : wmsOutOrderLineList) {
                //外键设置
                entity.setOrderNum(wmsOutOrderHeader.getOrderNum());
                wmsOutOrderLineMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMainOutOrderHeader(WmsOutOrderHeader wmsOutOrderHeader, List<WmsOutOrderLine> wmsOutOrderLineList) {
        setWmsOrderHeaderField(wmsOutOrderHeader);
        wmsOutOrderHeaderMapper.insert(wmsOutOrderHeader);
        if (wmsOutOrderLineList != null && wmsOutOrderLineList.size() > 0) {
            for (WmsOutOrderLine entity : wmsOutOrderLineList) {
                //外键设置
                entity.setOrderNum(wmsOutOrderHeader.getOrderNum());
                entity.setCusCode(wmsOutOrderHeader.getCusCode());
                entity.setCusName(wmsOutOrderHeader.getCusName());
                entity.setOrderLineStatus(CommonWms.WAIT_FOR_OUT);
                entity.setGoodsOkQua("0");
                entity.setGoodsSyQua("0");
                entity.setGoodsUnitName(wmsGetNameService.getName(entity.getGoodsUnitCode(), CommonWms.UNIT_CODE));

                //做出库推荐  先进先出原则
                // TODO 暂时不考虑缺货问题，仅仅做推荐
                List<WmsInventory> wmsInventories = wmsInventoryMapper.selectList(new LambdaQueryWrapper<WmsInventory>()
                        .eq(WmsInventory::getCusCode, entity.getCusCode())
                        .eq(WmsInventory::getGoodsBatch, entity.getGoodsBatch())
                        .eq(WmsInventory::getGoodsUnitCode, entity.getGoodsUnitCode())
                        .eq(WmsInventory::getGoodsCode, entity.getGoodsCode())
                        .orderByDesc(WmsInventory::getCreateTime)
                );
                if (CollUtil.isNotEmpty(wmsInventories)) {
                    WmsInventory wmsInventory = wmsInventories.get(0);
                    entity.setBinCode(wmsInventory.getBinCode());
                    entity.setTrayCode(wmsInventory.getTrayCode());
                    entity.setKwCode(wmsInventory.getKwCode());
                }
                wmsOutOrderLineMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(WmsOutOrderHeader wmsOutOrderHeader, List<WmsOutOrderLine> wmsOutOrderLineList) {

        if (!wmsOutOrderHeader.getOrderStatus().equals(CommonWms.WAIT_FOR_OUT)) {
            throw new JeecgBootException("订单状态不是待出库，不允许修改");
        }

        //组装欠缺名称
//        wmsOutOrderHeader.setCusName(wmsGetNameService.getName(wmsOutOrderHeader.getCusCode(), CommonWms.CUS_CODE));
//        wmsOutOrderHeader.setSupName(wmsGetNameService.getName(wmsOutOrderHeader.getSupCode(), CommonWms.SUPLY_CODE));
//        wmsOutOrderHeader.setOrderTypeName(wmsGetNameService.getName(wmsOutOrderHeader.getOrderTypeCode(), CommonWms.ORDER_TYPE_CODE));
        wmsOutOrderHeaderMapper.updateById(wmsOutOrderHeader);

        //只有子表状态时待出库才允许修改
        List<WmsOutOrderLine> wmsOutOrderLineLists = new ArrayList<>();
        if (wmsOutOrderLineList != null && wmsOutOrderLineList.size() > 0) {
            for (WmsOutOrderLine entity : wmsOutOrderLineList) {
                if (entity.getOrderLineStatus().equals(CommonWms.WAIT_FOR_OUT)) {
                    //1.先删除子表数据
                    wmsOutOrderLineMapper.deleteById(entity.getId());
                    wmsOutOrderLineLists.add(entity);
                }
            }
        }

        //2.子表数据重新插入
        if (wmsOutOrderLineLists != null && wmsOutOrderLineLists.size() > 0) {
            for (WmsOutOrderLine entity : wmsOutOrderLineLists) {
                entity.setId("");
                entity.setOrderNum(wmsOutOrderHeader.getOrderNum());
                entity.setCusCode(wmsOutOrderHeader.getCusCode());
                entity.setCusName(wmsOutOrderHeader.getCusName());
                entity.setOrderLineStatus(CommonWms.WAIT_FOR_OUT);
                entity.setGoodsOkQua("0");
                entity.setGoodsSyQua("0");
                entity.setGoodsUnitName(wmsGetNameService.getName(entity.getGoodsUnitCode(), CommonWms.UNIT_CODE));

                //做出库推荐  先进先出原则
                // TODO 暂时不考虑缺货问题，仅仅做推荐
                List<WmsInventory> wmsInventories = wmsInventoryMapper.selectList(new LambdaQueryWrapper<WmsInventory>()
                        .eq(WmsInventory::getCusCode, entity.getCusCode())
                        .eq(WmsInventory::getGoodsBatch, entity.getGoodsBatch())
                        .eq(WmsInventory::getGoodsUnitCode, entity.getGoodsUnitCode())
                        .eq(WmsInventory::getGoodsCode, entity.getGoodsCode())
                        .orderByDesc(WmsInventory::getCreateTime)
                );
                if (CollUtil.isNotEmpty(wmsInventories)) {
                    WmsInventory wmsInventory = wmsInventories.get(0);
                    entity.setBinCode(wmsInventory.getBinCode());
                    entity.setTrayCode(wmsInventory.getTrayCode());
                    entity.setKwCode(wmsInventory.getKwCode());
                }
                wmsOutOrderLineMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        WmsOutOrderHeader outOrderHeader = wmsOutOrderHeaderMapper.selectById(id);
        wmsOutOrderLineMapper.deleteByMainId(outOrderHeader.getOrderNum());
        wmsOutOrderHeaderMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            WmsOutOrderHeader outOrderHeader = wmsOutOrderHeaderMapper.selectById(id);
            wmsOutOrderLineMapper.deleteByMainId(outOrderHeader.getOrderNum());
            wmsOutOrderHeaderMapper.deleteById(id);
        }
    }


    private void setWmsOrderHeaderField(WmsOutOrderHeader wmsOutOrderHeader) {
        //生成订单号
        int count = Math.toIntExact(this.lambdaQuery()
                .eq(WmsOutOrderHeader::getOrderTypeCode, wmsOutOrderHeader.getOrderTypeCode())
                .apply("date_format(create_time,'%Y-%m-%d') = '" + DateUtil.today() + "'")
                .count());
        wmsOutOrderHeader.setOrderNum(wmsOutOrderHeader.getOrderTypeCode()
                + DateUtils.date2Str(new SimpleDateFormat("yyyyMMdd"))
                + "-"
                + String.format("%04d", (count + 1)));
        wmsOutOrderHeader.setOrderStatus(CommonWms.WAIT_FOR_OUT);
//        组装欠缺名称
//        wmsOutOrderHeader.setCusName(wmsGetNameService.getName(wmsOutOrderHeader.getCusCode(), CommonWms.CUS_CODE));
//        wmsOutOrderHeader.setSupName(wmsGetNameService.getName(wmsOutOrderHeader.getSupCode(), CommonWms.SUPLY_CODE));
//        wmsOutOrderHeader.setOrderTypeName(wmsGetNameService.getName(wmsOutOrderHeader.getOrderTypeCode(), CommonWms.ORDER_TYPE_CODE));
    }

}
